/**
 * Created by
 * User: Tang Yong Di
 * Date: 2016/10/26
 */

window.Report = function () {
};
window.Report.prototype = {
    userInfo: {},           // 用户信息
    storeId: 0,             // 当前门店id
    restaurants: [],        // 门店信息数组
    router: '',             // 当前router地址
    startDate: '',          // 开始时间
    endDate: '',            // 结束时间
    dateMode: 0,            // 0--天 1--周 2--月 3--自定义
    dataSort: 'desc',       // 滞销/畅销
    leftMenuToggle : null,  // 左边菜单
    init: function () {
    },
    initLeftMenuToggle: function () {
        var _this = this;
        report.leftMenuToggle = XS.util.mainMenuToggle(function (target, show) {
            if (show && !$('.user-info').hasClass('loaded')) {
                //要重写绘制头像
                _this.renderUserInfo();
            }
        });
    },
    renderUserInfo: function () {
        var $userInfo = $('.user-info');
        $userInfo.addClass('loaded');

        var headPicture = report.userInfo['HeadPicture'];
        var $img = $('<img/>').attr({'src': headPicture});
        $userInfo.find('.head-picture').append($img);

        var nickname = report.userInfo['NickName'] || '获取失败';
        $userInfo.find('.nickname').html(nickname);
    },
    initDateModeValue: function (mode) {
        if (mode == 0) {
            report.startDate = report.format(moment());
            report.endDate = report.format(moment());
        } else if (mode == 1) {
            report.startDate = report.format(moment().startOf('week'));
            report.endDate = report.format(moment());
        } else if (mode == 2) {
            report.startDate = report.format(moment().startOf('month'));
            report.endDate = report.format(moment());
        } else {
            report.startDate = report.format(moment().startOf('week'));
            report.endDate = report.format(moment());
        }
    },
    initDateMode: function () {
        var mode = report.dateMode;
        $('.data-mode-' + mode).addClass('active').siblings().removeClass('active');
        this.changeDataMode(mode);
    },
    initDataSort: function () {
        var sort = report.dataSort;
        $('.data-sort-' + sort).addClass('btn-primary').siblings().removeClass('btn-primary');
    },
    changeDataMode: function (mode) {
        var _this = this;
        if (mode == 0) {
            _this.dateDayInit();
        } else if (mode == 1) {
            _this.dateWeekInit();
        } else if (mode == 2) {
            _this.dateMonthInit();
        } else {
            _this.rangeBasicInit();
        }
    },
    dateDayInit: function () {
        var _this = this;
        _this.showDay(true);
        if (moment(report.startDate).isSame(report.format(moment()), 'day')) {
            $('#rangeDateDay').text('今天');
        } else if (moment(report.startDate).isSame(report.format(moment().subtract(1, 'days')), 'day')) {
            $('#rangeDateDay').text('昨天');
        } else {
            $('#rangeDateDay').text(report.startDate);
        }
    },
    dateWeekInit: function () {
        var _this = this;
        _this.showDay(true);
        if (moment(report.startDate).isSame(report.format(moment()), 'week')) {
            $('#rangeDateDay').text('本周');
        } else {
            $('#rangeDateDay').text(report.startDate + '至' + report.endDate);
        }
        //$('#rangeDateDay').text(moment().add(6, 'days').calendar());
    },
    dateMonthInit: function () {
        var _this = this;
        _this.showDay(true);
        if (moment(report.startDate).isSame(report.format(moment()), 'month')) {
            $('#rangeDateDay').text('本月');
        } else {
            $('#rangeDateDay').text(_this.format(moment(report.startDate), 'YYYY-MM'));
        }
    },
    rangeBasicInit: function () {
        var _this = this;
        _this.showDay(false);
        var $rangeDateBox = $('#rangeDateBox');
        var $rangeDate = $('#rangeDateBox').find('span');
        $rangeDate.html(report.startDate + '至' + report.endDate);
        $rangeDateBox.mobiscroll().range({
            lang: 'zh',
            display: 'bottom',
            mode: 'mixed',
            max: new Date(new Date()),
            maxRange: 1000 * 60 * 60 * 24 * 30,
            onSet: function (event, inst) {
                var startDate = _this.format(moment(inst._startDate));
                var endDate = _this.format(moment(inst._endDate));
                $rangeDate.html(startDate + '至' + endDate);
                report.startDate = startDate;
                report.endDate = endDate;
            },
            onBeforeShow: function (event, inst) {
                $rangeDateBox.mobiscroll('setVal', [moment(_this.startDate).toDate(), moment(_this.endDate).toDate()]);
            }
        });
    },
    showDay: function (flag) {
        if (flag) {
            $('#rangeDateDayBox').show();
            $('#rangeDateBox').hide();
        } else {
            $('#rangeDateDayBox').hide();
            $('#rangeDateBox').show();
        }
    },
    format: function (moment, type) {
        var _format = type || 'YYYY-MM-DD';
        return moment.format(_format);
    },
    subtractMode: function () {
        var mode = report.dateMode;
        var startDate = report.startDate;
        if (mode == 0) {
            report.startDate = report.format(moment(startDate).subtract(1, 'days'));
            report.endDate = report.format(moment(startDate).subtract(1, 'days'));
        } else if (mode == 1) {
            report.startDate = report.format(moment(startDate).subtract(7, 'days').startOf('week'));
            report.endDate = report.format(moment(startDate).subtract(7, 'days').endOf('week'));
        } else if (mode == 2) {
            report.startDate = report.format(moment(startDate).subtract(1, 'months').startOf('month'));
            report.endDate = report.format(moment(startDate).subtract(1, 'months').endOf('month'));
        } else {
            //其他的就没有增加减少日期了
        }
        return true;
    },
    addMode: function () {
        var mode = report.dateMode;
        var startDate = report.startDate;
        if (mode == 0) {
            if (moment(startDate).isSame(report.format(moment()), 'day')) {
                return false;
            }
            report.startDate = report.format(moment(startDate).add(1, 'days'));
            report.endDate = report.format(moment(startDate).add(1, 'days'));
        } else if (mode == 1) {
            if (moment(startDate).isSame(report.format(moment()), 'week')) {
                return false;
            }
            report.startDate = report.format(moment(startDate).add(7, 'days').startOf('week'));
            report.endDate = report.format(moment(startDate).add(7, 'days').endOf('week'));
        } else if (mode == 2) {
            if (moment(startDate).isSame(report.format(moment()), 'month')) {
                return false;
            }
            report.startDate = report.format(moment(startDate).add(1, 'months').startOf('month'));
            report.endDate = report.format(moment(startDate).add(1, 'months').endOf('month'));
        } else {
            //其他的就没有增加减少日期了
        }
        return true;
    },
    showLoading: function () {
        var $body = $('body');
        var $loading = $('<div class="report-data-loading-new"><div class="loading"></div></div>');
        $body.append($loading);
    },
    hideLoading: function () {
        $('.report-data-loading-new').remove();
    }
};
var report = new Report();
report.startDate = report.format(moment());
report.endDate = report.format(moment());

$(function () {
    //这里可以自定义模板的读取数据的符号，如果放在jsp可能会有冲突，所以暂时先用的html，也没有改这个设置。
    _.templateSettings = {
        evaluate: /<%([\s\S]+?)%>/g,    //执行方法的代码块符号
        interpolate: /<%=([\s\S]+?)%>/g,   //获取参数的代码块符号
        escape: /<%-([\s\S]+?)%>/g    //需要转义的代码块符号
    };
    var EventHub = _.extend({}, Backbone.Events);

    //页面需要用到的空model，因为接口返回的数据一边都是已data为最外层key的json，如果要做一些数据判断或者操作就会比较麻烦
    //这里一般是直接new个PageMode，并把返回的json的model.get('data')放进这个PageMode中，再做操作
    var PageMode = Backbone.Model.extend({});
    //报表Model
    var ReportMode = Backbone.Model.extend({});

    //用户信息Mode
    var UserInfoMode = Backbone.Model.extend({
        url: 'http://localhost/restaurant/backbone/userInfo',
        parse: function (response) {
            return (response);
        }
    });
    //门店列表Model
    var RestaurantMode = Backbone.Model.extend({
        url: 'http://localhost/restaurant/backbone/restaurants',
        parse: function (response) {
            return (response);
        }
    });

    //主View
    var MainView = Backbone.View.extend({
        el: $('#page-report'),
        statsTemplate: _.template($('#index-template').html()),
        initialize: function () {
            var _this = this;
            EventHub.on('routedToMain', function () {
                _this.renderMain();
            });
            EventHub.on('routedToOperatingLive', function (reportMode) {
                _this.renderOperatingLive(reportMode);
            });
            EventHub.on('routedToBusinessStatistics', function (historyBillSummaryModel, historyPaymentSummaryModel, historyDepartmentIncomeSummary) {
                _this.renderBusinessStatistics(historyBillSummaryModel, historyPaymentSummaryModel, historyDepartmentIncomeSummary);
            });
            EventHub.on('routedToSalesRanking', function (reportMode) {
                _this.renderSalesRanking(reportMode);
            });
        },
        events: {
            "click .menu-list li": "hrefRouter",
            "change #restaurant-select": "reloadThisPageByStoreId",
            "change #rangeDateBox": "reloadThisPageByDate",
            "click .date-chooser-new-mode li": "changeDateMode",
            "click #data-prev": "prevDate",
            "click #data-next": "nextDate",
            "click .data-sort": "changeSort"
        },
        hrefRouter: function (e) {
            var _this = $(e.target);
            //_this.addClass('active').siblings().remove('active');
            window.location.href = _this.data('href');
        },
        reloadThisPageByStoreId: function (e) {
            var _this = $(e.target);
            report.storeId = _this.val();
            this.reloadThisPage();
        },
        reloadThisPageByDate: function () {
            this.reloadThisPage();
        },
        changeDateMode: function (e) {
            var _element = $(e.target);
            var dateMode = _element.data('mode');
            if (dateMode == report.dateMode) {
                return;
            }
            _element.addClass('active').siblings().removeClass('active');
            report.dateMode = dateMode;
            report.initDateModeValue(dateMode);
            this.reloadThisPage();
        },
        prevDate: function (e) {
            if (report.subtractMode()) {
                this.reloadThisPage();
            }
        },
        nextDate: function (e) {
            if (report.addMode()) {
                this.reloadThisPage();
            }
        },
        changeSort: function (e) {
            var _element = $(e.target);
            var dataSort = _element.data('sort');
            if (dataSort !== report.dataSort) {
                report.dataSort = dataSort;
                this.reloadThisPage();
            }
        },
        reloadThisPage: function () {
            //同时触发当前的router时，backbone不会做任何动作，所以这里先跳转一次主页，再跳转当前页，相当于无刷新页面刷新数据，前台页面展现没有影响
            router.navigate("");
            router.navigate(report.router, {trigger: true});
        },
        renderMain: function () {
            var restaurantsTemplate = _.template('<span class="navbar-brand">迅手智慧餐饮</span>');
            var reportTemplate = _.template($('#report-template').html());
            var reportBody = _.template($('#main-template').html());
            this.$el.html(this.statsTemplate({
                pageDetail: reportTemplate({
                    reportTitle: restaurantsTemplate({}),
                    reportHead: '',
                    reportBody: reportBody({})
                })
            }));
            report.initLeftMenuToggle();
        },
        renderOperatingLive: function (reportMode) {
            var restaurantMode = new PageMode();
            restaurantMode.set('storeId', report.storeId);
            restaurantMode.set('data', report.restaurants);
            var restaurantsTemplate = _.template($('#restaurants-template').html());
            var reportTemplate = _.template($('#report-template').html());
            var reportBody = _.template($('#operating-template').html());
            this.$el.html(this.statsTemplate({
                pageDetail: reportTemplate({
                    reportTitle: restaurantsTemplate(restaurantMode.attributes),
                    reportHead: '',
                    reportBody: reportBody(reportMode.get('data'))
                })
            }));
            report.initLeftMenuToggle();
        },
        renderBusinessStatistics: function (historyBillSummaryModel, historyPaymentSummaryModel, historyDepartmentIncomeSummary) {
            var pageMode = new PageMode();
            pageMode.set("historyBillSummaryModel", historyBillSummaryModel.get('data'));
            pageMode.set("historyPaymentSummaryModel", historyPaymentSummaryModel.get('data'));
            pageMode.set("historyDepartmentIncomeSummary", historyDepartmentIncomeSummary.get('data'));
            var restaurantMode = new PageMode();
            restaurantMode.set('storeId', report.storeId);
            restaurantMode.set('data', report.restaurants);
            var restaurantsTemplate = _.template($('#restaurants-template').html());
            var reportTemplate = _.template($('#report-template').html());
            var reportHead = _.template($('#chooseDate-template').html());
            var reportBody = _.template($('#businessStatistics-template').html());
            this.$el.html(this.statsTemplate({
                pageDetail: reportTemplate({
                    reportTitle: restaurantsTemplate(restaurantMode.attributes),
                    reportHead: reportHead({}),
                    reportBody: reportBody(pageMode.attributes)
                })
            }));
            report.initLeftMenuToggle();
            report.initDateMode();
        },
        renderSalesRanking: function (reportMode) {
            //按DepartmentName重新组装新的reportMode
            var rptMode = new ReportMode();
            _.each(reportMode.get('data'), function (item) {
                var attr = item.DepartmentName;
                var arrays = [];
                if (rptMode.has(attr)) {
                    arrays = rptMode.get(attr);
                }
                arrays.push({
                    'Sort': item.Sort,
                    'DepartmentName': item.DepartmentName,
                    'DishName': item.DishName,
                    'SaleQuantity': item.SaleQuantity,
                    'SaleAmount': item.SaleAmount
                });
                rptMode.set(attr, arrays);
            });
            var newReportMode = new ReportMode();
            newReportMode.set('data', rptMode.attributes);
            var restaurantMode = new PageMode();
            restaurantMode.set('storeId', report.storeId);
            restaurantMode.set('data', report.restaurants);
            var restaurantsTemplate = _.template($('#restaurants-template').html());
            var reportTemplate = _.template($('#report-template').html());
            var reportHead = _.template($('#chooseDate-template').html());
            var reportBody = _.template($('#renderSales-template').html());
            this.$el.html(this.statsTemplate({
                pageDetail: reportTemplate({
                    reportTitle: restaurantsTemplate(restaurantMode.attributes),
                    reportHead: reportHead({}),
                    reportBody: reportBody(newReportMode.attributes)
                })
            }));
            report.initLeftMenuToggle();
            report.initDateMode();
            report.initDataSort();
        },
        render: function () {
            this.$el.html(this.statsTemplate({
                pageDetail: 'asdasd'
            }));
        }
    });
    var mainView = new MainView({});

    //路由
    var MainRouter = Backbone.Router.extend({
        routes: {
            //主页
            "": "main",
            //经营实况
            "operatingLive": "operatingLive",
            //营业统计
            "businessStatistics": "businessStatistics",
            //销售排行
            "salesRanking": "salesRanking",
            //日常收支
            "dailyPayments": "dailyPayments",
            //库房管理
            "stockManage": "stockManage",
            //员工信息
            "employeeInformation": "employeeInformation",
            //门店对比
            "storeComparison": "storeComparison"
        },
        main: function () {
            report.router = "";
            report.leftMenuToggle && report.leftMenuToggle.toggle();
            report.showLoading();
            this.initPublicData(function () {
                EventHub.trigger('routedToMain');
                report.hideLoading();
            });
        },
        operatingLive: function () {
            report.router = "operatingLive";
            report.leftMenuToggle && report.leftMenuToggle.toggle();
            report.showLoading();
            this.initPublicData(function () {
                var operatingLiveMode = new ReportMode();
                operatingLiveMode.fetch({
                    url: 'http://localhost/restaurant/backbone/operating',
                    data: {storeId: report.storeId},
                    success: function (reportModel) {
                        if (reportModel.get("result") == 0) {
                            EventHub.trigger('routedToOperatingLive', reportModel);
                        } else {
                            alert(reportModel.get("message"));
                        }
                        report.hideLoading();
                    }, error: function () {
                        alert('error');
                    }
                });
            });
        },
        businessStatistics: function () {
            report.router = "businessStatistics";
            report.leftMenuToggle && report.leftMenuToggle.toggle();
            report.showLoading();
            var requestDate = {
                storeId: report.storeId,
                startDate: report.startDate,
                endDate: report.endDate
            };
            //请求门店集合
            this.initPublicData(function () {
                //请求历史账单汇总
                var businessStatisticsMode = new ReportMode();
                businessStatisticsMode.fetch({
                    url: 'http://localhost/restaurant/backbone/historyBillSummary',
                    data: requestDate,
                    success: function (historyBillSummaryModel) {
                        if (historyBillSummaryModel.get("result") == 0) {
                            //请求历史付款汇总
                            var historyPaymentSummary = new ReportMode();
                            historyPaymentSummary.fetch({
                                url: 'http://localhost/restaurant/backbone/historyPaymentSummary',
                                data: requestDate,
                                success: function (historyPaymentSummaryModel) {
                                    if (historyPaymentSummaryModel.get("result") == 0) {
                                        //请求历史部门收入汇总
                                        var historyDepartmentIncomeSummaryMode = new ReportMode();
                                        historyDepartmentIncomeSummaryMode.fetch({
                                            url: 'http://localhost/restaurant/backbone/historyDepartmentIncomeSummary',
                                            data: requestDate,
                                            success: function (historyDepartmentIncomeSummary) {
                                                if (historyDepartmentIncomeSummary.get("result") == 0) {
                                                    EventHub.trigger('routedToBusinessStatistics', historyBillSummaryModel, historyPaymentSummaryModel, historyDepartmentIncomeSummary);
                                                } else {
                                                    alert(historyDepartmentIncomeSummary.get("message"));
                                                }
                                                report.hideLoading();
                                            }, error: function () {
                                                alert('error');
                                            }
                                        });

                                    } else {
                                        alert(historyPaymentSummaryModel.get("message"));
                                    }
                                }, error: function () {
                                    alert('error');
                                }
                            });
                        } else {
                            alert(historyBillSummaryModel.get("message"));
                        }
                    }, error: function () {
                        alert('error');
                    }
                });
            });
        },
        salesRanking: function () {
            report.router = "salesRanking";
            report.leftMenuToggle && report.leftMenuToggle.toggle();
            report.showLoading();
            this.initPublicData(function () {
                var operatingLiveMode = new ReportMode();
                operatingLiveMode.fetch({
                    url: 'http://localhost/restaurant/backbone/salesRanking',
                    data: {
                        storeId: report.storeId,
                        startDate: report.startDate,
                        endDate: report.endDate,
                        sort: report.dataSort
                    },
                    success: function (reportModel) {
                        if (reportModel.get("result") == 0) {
                            EventHub.trigger('routedToSalesRanking', reportModel);
                        } else {
                            alert(reportModel.get("message"));
                        }
                        report.hideLoading();
                    }, error: function () {
                        alert('error');
                    }
                });
            });
        },
        dailyPayments: function () {
            report.router = "dailyPayments";
            alert("日常收支")
        },
        stockManage: function () {
            report.router = "stockManage";
            alert("库房管理")
        },
        employeeInformation: function () {
            report.router = "employeeInformation";
            alert("员工信息")
        },
        storeComparison: function () {
            report.router = "storeComparison";
            alert("门店对比")
        },
        //初始化公用信息，包括门店列表、用户信息
        initPublicData: function (fun) {
            if (_.isEqual({}, report.userInfo) || report.storeId == 0) {
                var userInfoMode = new UserInfoMode();
                userInfoMode.fetch({
                    success: function (userInfoMode) {
                        if (userInfoMode.get("result") == 0) {
                            report.userInfo = userInfoMode.get('data');
                            var restaurantMode = new RestaurantMode();
                            restaurantMode.fetch({
                                success: function (restaurantMode) {
                                    if (restaurantMode.get("result") == 0) {
                                        report.storeId = _.first(restaurantMode.get('data')).Id;
                                        report.restaurants = restaurantMode.get('data');
                                        if (typeof fun == 'function') {
                                            fun();
                                        }
                                    } else {
                                        alert(restaurantMode.get("message"));
                                    }
                                }
                            });
                        } else {
                            alert(userInfoMode.get("message"));
                        }
                    }
                });
            } else {
                if (typeof fun == 'function') {
                    fun();
                }
            }
        }
    });
    var router = new MainRouter();
    Backbone.history.start();
});